import React from "react";
import { Tabs, Modal, Table, Row, Popconfirm, Button, Form, Input, DatePicker} from "antd";
import _uniqBy from "lodash/uniqBy";
import { connect } from "dva";
import TreeSelect from "../flowdetailpannel/TreeSelect";
import styles from "./ReadHandleForm.less";

import { openNotificationWithIcon } from "../../utils/comm.js";

const { TabPane } = Tabs;

const isTrue = true;
const { TextArea } = Input;
const activeTypeArr = [
  "STA",
  "ORG",
  "ROL",
  "GROUP",
  "POSITION",
];
const typeLabelMap = { STA: "人员", ORG: "组织", ROL: "角色", GROUP: "用户组", POSITION: "岗位" };
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};
const formItemLayout2 = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 21 },
  },
};

@connect(({ loading }) => ({
  loading: loading.effects["FlowHandle/dealReadDoData"],
}))
@Form.create()
class TransactorSelect extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.treeRef = {};
    // this.activeType = 'STA';
    this.state = {
      allSelectData: "",
      activeType: "STA",
      selectedSTAKeys: [],
    };
  }

  componentDidMount() {}

  componentDidUpdate(preProps) {
    const { visible, selectData } = this.props;
    if (visible !== preProps.visible) {
      if (visible) {
        this.setTreesSelectKeys(selectData);
      } else {
        this.setTreesSelectKeys([]);
      }
    }
  }

  componentWillUnmount() {
    // this.activeType = 'STA';
  }

  getTreeRef = (type, treeThis) => {
    this.treeRef[type] = treeThis;
  };

  onTabChage = activeType => {
    // this.activeType = activeType;
    this.setState({ activeType });
  };

  // 选中人员
  onCheckedRows = newSelectedRowKeys => {
    const { selectData } = this.props;
    const { allSelectData } = this.state;
    const tempSelect = allSelectData || selectData;
    const otherData =
      (Array.isArray(tempSelect) && tempSelect.filter(v => v.type !== "STA")) ||
      [];
    this.setState({
      allSelectData: _uniqBy([...otherData, ...newSelectedRowKeys], "name"),
    });
  };

  // 选中项
  onCheckedNodes = (
    ischecked,
    node,
    checkedNodes,
    newSelectNodes = [],
    prevSelectedKeys = [],
  ) => {
    const { selectData = [] } = this.props;
    const { allSelectData, activeType } = this.state;
    let selectDatas = allSelectData || selectData;
    if (newSelectNodes) {
      if (ischecked) {
        // 过滤新增的选择的node
        const typeNodes = newSelectNodes.filter(item => {
          if (selectDatas.length === 0) return true;
          return !selectDatas.some(sItem => {
            return sItem.code === item.code && sItem.type === item.type;
          });
        });
        selectDatas = [...selectDatas, ...typeNodes];
        /*
      } else if (newSelectNodes.length === 0) {
        selectDatas = selectDatas.filter(item => item.type !== activeType);
      } else {
        selectDatas = selectDatas.filter(item => {
          const isExit = newSelectNodes.some(sItem => {
            return (sItem.code === item.code && sItem.type === item.type);
          });
          return (activeType !== item.type || isExit);
        });
      }
      */
      } else {
        // 比对 prevSelectedKeys与newNodes，删除被去除的项

        const existedMap = (newSelectNodes || []).reduce((map, { code }) => {
          map[code] = true;
          return map;
        }, {});

        const removedKeyMap = (prevSelectedKeys || []).reduce((map, k) => {
          if (!existedMap[k]) {
            map[k] = true;
          }
          return map;
        }, {});

        selectDatas = selectDatas.filter(item => {
          return activeType !== item.type || !removedKeyMap[item.code];
        });
      }
      this.setState({ allSelectData: selectDatas });
      this.setTreesSelectKeys(selectDatas);
    }
  };

  // 重置树中的反显项
  setTreesSelectKeys = selectDatas => {
    activeTypeArr.forEach(activeType => {
      setTimeout(() => {
        const selectedTypeData = selectDatas.filter(
          sitem => sitem.type === activeType,
        );
        const selectedKeys = selectedTypeData.map(sitem => sitem.code);
        const nowTreeRef = this.treeRef[activeType];
        if (nowTreeRef)
          nowTreeRef.setTreeSelectData(selectedKeys, selectedTypeData);
      }, 300);
    });
  };

  // 确定
  handleOk = () => {
    const { form, dispatch, onCancel, processInstanceId, taskId, getList } = this.props;
    const { allSelectData } = this.state;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: "FlowHandle/dealReadDoData",
        payload: {
          processInstanceId,
          taskId,
          sendUserCode: sessionStorage.getItem("USER_CODE"),
          sendUserName: sessionStorage.getItem("USER_NAME"),
          shouldCompleteTime: (values.date).format('YYYY-MM-DD'),
          comment: values.comment,
          readDoUsers: allSelectData,
        },
      }).then(({ errCode, errMsg }) => {
        if (errCode === 0) {
          onCancel();
          openNotificationWithIcon("success", "", "阅办发送成功");
          if (getList instanceof Function) {
            getList();
          }
          setTimeout(() => {
            this.setState({ allSelectData: "", activeType: "STA" });
            this.setTreesSelectKeys([]);
          }, 100);
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    });
  };

  handleCancel = () => {
    const { onCancel } = this.props;
    if (onCancel) {
      onCancel();
      this.setState({ allSelectData: "", activeType: "STA" });
    }
  };

  inputItem = node => {
    this.input = node;
  };

  handleDeleteUsers = (candidateUsers, deleteAll = false, selectedKeys) => {
    const { selectedSTAKeys } = this.state;
    const removedKeyMaps = (selectedKeys || selectedSTAKeys || []).reduce(
      (a, k) => {
        a[k] = true;
        return a;
      },
      {},
    );
    let newUsers;
    let removedIndexes = [];
    if (deleteAll) {
      newUsers = [];
      removedIndexes = candidateUsers.map((e, i) => i);
    } else {
      newUsers = candidateUsers.filter((nt, idx) => {
        if (removedKeyMaps[nt.code]) {
          removedIndexes.push(idx);
          return false;
        }
        return true;
      });
    }
    this.setState({ selectedSTAKeys: [], allSelectData: newUsers });
    this.setTreesSelectKeys(newUsers);
  };

  renderButtons = (type, allSelectData) => {
    const {
      selectedSTAKeys = [],
      selectedVARKeys = [],
    } = this.state;
    const {
      disable,
    } = this.props;
    let suffix = "变量";
    let keys = selectedVARKeys;
    if (type === "STA") {
      suffix = "人员";
      keys = selectedSTAKeys;
    }
    return (
      <Row
        className={styles.buttons}
        justify="space-between"
        style={{ marginTop: 16, marginLeft: 38 }}
        type="flex"
      >
        {!disable && keys.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除当前选中${typeLabelMap[type]}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                },
                () => {
                  this.handleDeleteUsers(allSelectData, false, keys);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>删除</Button>
          </Popconfirm>
        ) : (
          <Button disabled>删除</Button>
        )}
        {!disable && allSelectData.length > 0 ? (
          <Popconfirm
            placement="top"
            title={`请确认是否删除所有${suffix}`}
            onConfirm={() => {
              this.setState(
                {
                  selectedSTAKeys: [],
                  selectedVARKeys: [],
                },
                () => {
                  this.handleDeleteUsers(allSelectData, true);
                  this.forceUpdate();
                },
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>全删</Button>
          </Popconfirm>
        ) : (
          <Button disabled>全删</Button>
        )}
      </Row>
    );
  };

  render() {
    const {
      dispatch,
      visible,
      wrapClassName,
      selectData = [],
      appId,
      disable,
      form,
      loading,
    } = this.props;
    const { allSelectData, activeType, selectedSTAKeys } = this.state;
    const selectDatas = allSelectData || selectData;
    const { getFieldDecorator } = form;

    return (
      <Modal
        title="选择【发送阅办】处理人"
        centered
        width='auto'
        destroyOnClose
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        confirmLoading={loading}
        wrapClassName={`${styles.user_modal} ${wrapClassName}`}
      >
        <>
          <div className={styles.content}>
            <div className={styles.transactor_box}>
              <div className={styles.tree_box}>
                <Tabs
                  defaultActiveKey={activeType}
                  activeKey={activeType}
                  animated={false}
                  onChange={this.onTabChage}
                >
                  <TabPane tab="选择人员" key="STA" forceRender={isTrue}>
                    <TreeSelect
                      getTreeRef={treeThis => this.getTreeRef("STA", treeThis)}
                      directoryTree
                      dispatch={dispatch}
                      type="STA"
                      onCheckedRows={this.onCheckedRows}
                      defaultSelectData={selectDatas}
                    />
                  </TabPane>
                  <TabPane tab="选择组织" key="ORG" forceRender={isTrue}>
                    <TreeSelect
                      getTreeRef={treeThis => this.getTreeRef("ORG", treeThis)}
                      directoryTree
                      dispatch={dispatch}
                      isJustLoadOrg={isTrue}
                      checkStrictly={isTrue}
                      type="ORG"
                      onCheckedNodes={this.onCheckedNodes}
                    />
                  </TabPane>
                  <TabPane tab="选择角色" key="ROL" forceRender={isTrue}>
                    <TreeSelect
                      appId={appId}
                      getTreeRef={treeThis => this.getTreeRef("ROL", treeThis)}
                      dispatch={dispatch}
                      directoryTree
                      type="ROL"
                      onCheckedNodes={this.onCheckedNodes}
                    />
                  </TabPane>
                  <TabPane tab="用户组" key="GROUP" forceRender={isTrue}>
                    <TreeSelect
                      appId={appId}
                      getTreeRef={treeThis => this.getTreeRef("GROUP", treeThis)}
                      dispatch={dispatch}
                      directoryTree
                      type="GROUP"
                      onCheckedNodes={this.onCheckedNodes}
                    />
                  </TabPane>
                  <TabPane tab="岗位" key="POSITION" forceRender={isTrue}>
                    <TreeSelect
                      appId={appId}
                      getTreeRef={treeThis => this.getTreeRef("POSITION", treeThis)}
                      dispatch={dispatch}
                      directoryTree
                      type="POSITION"
                      onCheckedNodes={this.onCheckedNodes}
                    />
                  </TabPane>
                </Tabs>
              </div>
            </div>
            <div>
              <Table
                style={{ width: 300, marginLeft: 38 }}
                columns={[
                { title: "名称", dataIndex: "name" },
                {
                  title: "类型",
                  dataIndex: "type",
                  render: (v) => {
                    return typeLabelMap[v];
                  },
                },
              ]}
                dataSource={allSelectData}
                pagination={{
                pageSize: 5,
              }}
                rowKey="code"
                rowSelection={{
                fixed: true,
                getCheckboxProps: () => ({
                  disabled: disable,
                }),
                onChange: (keys) => {
                  if (disable) return;
                  this.setState({ selectedSTAKeys: keys });
                },
                selectedRowKeys: selectedSTAKeys,
              }}
                size="small"
              />
              {this.renderButtons("STA", allSelectData)}
            </div>
          
          </div>
          <div>
            <Form>
              <div className={styles.opinion}>流程意见</div>
              <Form.Item label="" {...formItemLayout}>
                {getFieldDecorator("comment", {
                    rules: [
                      { max: 1000, message: "请不要超过1000个字符" },
                      { required: true, message: "请输入流程意见" },
                    ],
                  })(<TextArea placeholder="请输入流程意见，最大限制在1000个字数内" rows={5} />)}
              </Form.Item>
              <Form.Item label="应完成时间" {...formItemLayout2}>
                {getFieldDecorator("date", {
                    rules: [
                      { required: true, message: "请选择应完成时间" },
                    ],
                  })(<DatePicker />)}
              </Form.Item>
            </Form>
          </div>
        </>
      </Modal>
    );
  }
}
export default TransactorSelect;
